package com.example.logining.controller;

/**
 * @title: UserController
 * @author: wywang
 * @date: 2024/11/09
 * @description:
 **/

import com.example.logining.domain.dto.UserLoginDTO;
import com.example.logining.domain.dto.UserRegistrationDTO;
import com.example.logining.domain.result.Result;
import com.example.logining.domain.vo.LoginUserVO;
import com.example.logining.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/hello")
    @PreAuthorize("@exRoot.hasAuthority('/articles/*')")
    public ResponseEntity<String> hello() {
        return ResponseEntity.ok("Hello, World!");
    }

    @PostMapping("/login")
    public Result<LoginUserVO> login(@RequestBody UserLoginDTO request) {
        LoginUserVO userVO = userService.login(request.getUsername(), request.getPassword());
        if(userVO == null){
            return Result.error("用户不存在",401);
        }
        return Result.success(userVO);
    }

    @PostMapping("/register")
    public Result<String> register(@RequestBody UserRegistrationDTO registrationUser) {
        userService.registerUser(registrationUser);
        return Result.success("User registered successfully.");
    }

    @PostMapping("/logout")
    public Result<String> logout() {
        userService.logout();
        return Result.success("User logged out successfully.");
    }

}